<?

if (empty($_SERVER['DOCUMENT_ROOT'])) {
	$_SERVER['DOCUMENT_ROOT'] = "/var/www/vhosts/geographs.org/httpdocs/";
}

include($_SERVER['DOCUMENT_ROOT'].'/includes/functions.inc.php');
include($_SERVER['DOCUMENT_ROOT'].'/portals/config.php');
include($_SERVER['DOCUMENT_ROOT'].'/groups/database.php');

if (false) {
	init_session();

	if (empty($_SESSION['user_id'])) {
		include($_SERVER['DOCUMENT_ROOT'].'/portals/login.inc.php');
		exit;
	}
}

include($_SERVER['DOCUMENT_ROOT'].'/portals/filter.libs.php');

$id = intval(@$_GET['id']);
if ($id) {
	////
} else {

	//auto!



	$sql = "SELECT portal_id,linear_start_id FROM `portal` WHERE status_id = 1 AND linear_start_id > 0 AND last_sorted < DATE_SUB(NOW(),INTERVAL 7 DAY)";

	$portals = getAssoc($sql);

	foreach ($portals as $id => $gid) {

		$images = getAll("SELECT gridimage_id,wgs84_lat,wgs84_long FROM p2.gridimage{$id}_bi_view");
		
		
		$sort = 1;
		
		print "STARTING portal#$id with iamge#$gid and ".count($images)." images<BR>\n";
		
		
		$found = -1;
		foreach ($images as $idx => $im) {
			if ($gid == $im['gridimage_id']) {
				$found = $idx;
			}
		}
		if ($found == -1) {
			print("unable to find image for $id");
			continue;
		}
		print "FOUND {$images[$found]['gridimage_id']} as idx $found<BR>\n";
		$lat = $images[$found]['wgs84_lat'];
		$lng = $images[$found]['wgs84_long'];
		
		queryExecute("UPDATE p2.gridimage{$id}_bi SET custom_sort = $sort,custom_dist=0,updated=updated WHERE gridimage_id = $gid");
		
		unset($images[$found]); //remove it from the pile.
		
		
		
		while (count($images)) {
			
			$closest = -1;
			$distance = 99999999999;
			foreach ($images as $idx => $im) {
				$dist = pow($lat - $im['wgs84_lat'],2) + pow($lng - $im['wgs84_long'],2); //no need to sqrt we only 'sorting'
				if ($dist < $distance) {
					$closest = $idx;
					$distance = $dist;
				}
			}
			
			if ($closest > -1) {
				$gid = $images[$closest]['gridimage_id'];
				$sort++;
				
				$lat = $images[$closest]['wgs84_lat'];
				$lng = $images[$closest]['wgs84_long'];
				
				print "NEXT FOUND $gid = $sort<BR>\n";
				
				
				$cdist = sqrt($distance);
				queryExecute("UPDATE p2.gridimage{$id}_bi SET custom_sort = $sort,custom_dist=$cdist,updated=updated WHERE gridimage_id = $gid");
			
				unset($images[$closest]); //remove it from the pile.
								
				print count($images)." left<BR>\n";
			
			} else {
				die("NO NEXT FOUND FOR $gid\n");
			}
			
		}
		print "FINISHED $id<BR>\n";
		queryExecute("UPDATE portal SET last_sorted = NOW(),updated=updated WHERE portal_id = $id");
		
	}

}

print "<hr>done\n";
